package org.luxor.commons.security.config.admin;

import org.luxor.commons.security.component.*;
import org.luxor.commons.security.config.WebSecurityProperties;
import org.luxor.commons.security.constant.SecurityConstants;
import org.luxor.commons.security.utils.SecurityUtils;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Primary;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore;
import org.springframework.util.Assert;

/**
 * Web安全控制
 *
 * @author yanxinming
 */
@ConditionalOnWebApplication
public class AdminServerConfigurer extends ResourceServerConfigurerAdapter {

    private final WebSecurityProperties webSecurityProperties;
    private final UserDetailsService userDetailsService;
    private RedisTokenStore tokenStore;

    public AdminServerConfigurer(WebSecurityProperties webSecurityProperties,
                                 UserDetailsService userDetailsService) {

        Assert.notNull(webSecurityProperties, "Spring容器中找不到[webSecurityProperties]的实例化对象!");
        this.webSecurityProperties = webSecurityProperties;

        Assert.notNull(userDetailsService, "Spring容器中找不到[UserDetailsService]的实例化对象!");
        this.userDetailsService = userDetailsService;
    }

    @Bean
    @Primary
    public TokenStore tokenStore(RedisConnectionFactory connectionFactory) {
        tokenStore = new RedisTokenStore(connectionFactory);
        return tokenStore;
    }

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) {
        resources.authenticationEntryPoint(new RestAuthExceptionEntryPoint())
                .tokenExtractor(new RestBearerTokenExtractor(webSecurityProperties))
                .accessDeniedHandler(new RestAccessDeniedHandler()).tokenStore(tokenStore);
    }


    /**
     * 配置鉴权机制
     *
     * @param http
     * @throws Exception
     */
    @Override
    public void configure(HttpSecurity http) throws Exception {
        // 允许使用iframe 嵌套，避免swagger-ui 不被加载的问题
        http.headers().frameOptions().disable()
                .and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and().userDetailsService(this.userDetailsService).authorizeRequests()
                .antMatchers(SecurityConstants.DEFAULT_ANON_URIS).permitAll()
                .antMatchers(webSecurityProperties.getAnonUris()).permitAll()
                .anyRequest().authenticated()
                .and().formLogin().loginPage("/login").loginProcessingUrl("/login").permitAll()
                .successHandler(new RestAuthenticationSuccessHandler(tokenStore))
                .failureHandler(new RestAuthenticationFailureHandler())
                .and().logout().logoutUrl("/logout").permitAll()
                .logoutSuccessHandler(new RestLogoutSuccessHandler())
                .and().anonymous().principal(SecurityUtils.ANONYMUS)
                .and().exceptionHandling()
                .authenticationEntryPoint(new RestAuthExceptionEntryPoint()).accessDeniedHandler(new RestAccessDeniedHandler())
                .and().csrf().disable();
    }

    @Bean
    public ReloadableResourceBundleMessageSource messageSource(){
        ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
        messageSource.setBasename("classpath:org/springframework/security/messages_zh_CN");
        return messageSource;
    }

}
